<?php
/* 
 * ebiz front
 * 
 * CommonUtil
 * 
 * @author allen
 * 
 */
class CommonUtil 
{   
	
	private static $startTime;
	private static $endTime;
    
	
	public static function getUniqueKey(){
		return time();
	}
	
    public function formatCategoryId($str){    //delete the last location word ex: "1,2,3," to "1,2,3" 
        $len = strlen($str);
        $str = substr($str, 0, $len - 1);  
        return $str;
    }
	
    public static function getDefaultSrc($imageSize, $sslProtocol = "http"){ //give the image size and file extension , ex: '_200.png'
    	$config = $GLOBALS["config"]; 
    	$src = "$sslProtocol://".ConfigConstants::$iConstants.".".DOMAIN."/t/".$config['template_name']."/image/product"."_".$imageSize;
    	return $src;
    }
    
    //compare saleprice and dealprice then get the discountInfo
    public static function getDiscountlInfo($sale_price,$deal_price,$quantity){
        $saleTotal = number_format($sale_price*$quantity,2);
        $dealTotal = number_format($deal_price*$quantity,2);
        if($saleTotal>$dealTotal){
           return $discount=number_format($saleTotal-$dealTotal,2);
        }
        return $discount=0;
    }
    
    public static function microtime_float(){
	    list($usec, $sec) = explode(" ", microtime());
	    return ((float)$usec + (float)$sec);
	}
    
	
	public static function startTimeFunction(){
        $debug = $GLOBALS["debug"];
        if ($debug == 1 || DEBUG_INFO == 1){
			CommonUtil::$startTime = CommonUtil::microtime_float();
		}
	}
    
	public static function endTimeFunction(){
        $debug = $GLOBALS["debug"];
        $info = "";
		if ($debug == 1 || DEBUG_INFO == 1){
            CommonUtil::$endTime = CommonUtil::microtime_float();
            $usedTime = CommonUtil::$endTime - CommonUtil::$startTime;
            $info = "<hr/>This page has been running $usedTime seconds.";
            return $info;
        }else{
        	return $info;
        }
	}
    
	public static function getDBConnectionNumber(){
		$rNum = DBUtil::$db_r_execute_num;
		$wNum = DBUtil::$db_w_execute_num;
		if(!empty($rNum)){
			return " Database read operation $rNum times. ";
		}elseif(empty($rNum)){
			return "";
		}
		if(!empty($wNum)){
			return " Database write operation $wNum times. ";
		}elseif(empty($wNum)){
			return "";
		}
	}
	
	/**
	 * Interception of the multi-byte utf8 encoding string
	 */
    public static function utf8Substr($str, $from, $len){  
        return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.  
                            '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',  
                            '$1',$str);  
    }  
	

    /**
     * substr GB2312
     */
	public static function mysubstr($str, $start, $len) {
	    $tmpstr = "";
	    $strlen = $start + $len;
	    for($i = 0; $i < $strlen; $i++) {
	        if(ord(substr($str, $i, 1)) > 0xa0) {
	            $tmpstr .= substr($str, $i, 2);
	            $i++;
	        } else
	            $tmpstr .= substr($str, $i, 1);
	    }
	    return $tmpstr;
	}

    /**
     * UTF-8、GB2312
     * $sublen为1==1个中文
     */
	public static function cut_str($string, $sublen, $start = 0, $code = 'UTF-8') 
	{ 
	    if($code == 'UTF-8') 
	    { 
	        $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/"; 
	        preg_match_all($pa, $string, $t_string); 
	 
	        if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."..."; 
	        return join('', array_slice($t_string[0], $start, $sublen)); 
	    } 
	    else 
	    { 
	        $start = $start*2; 
	        $sublen = $sublen*2; 
	        $strlen = strlen($string); 
	        $tmpstr = ''; 
	 
	        for($i=0; $i< $strlen; $i++) 
	        { 
	            if($i>=$start && $i< ($start+$sublen)) 
	            { 
	                if(ord(substr($string, $i, 1))>129) 
	                { 
	                    $tmpstr.= substr($string, $i, 2); 
	                } 
	                else 
	                { 
	                    $tmpstr.= substr($string, $i, 1); 
	                } 
	            } 
	            if(ord(substr($string, $i, 1))>129) $i++; 
	        } 
	        if(strlen($tmpstr)< $strlen ) $tmpstr.= "..."; 
	        return $tmpstr; 
	    } 
	} 
	
	/**
	 * 针对英文
	 * $Length为1 == 一个英文长度
	 * 一个中文占2个长度
	 */
	public static function sysSubStr($String,$Length,$Append = false) 
	{ 
	    if (strlen($String) <= $Length ) 
	    { 
	        return $String; 
	    } 
	    else 
	    { 
	        $I = 0; 
	        while ($I < $Length) 
	        { 
	            $StringTMP = substr($String,$I,1); 
	            if ( ord($StringTMP) >=224 ) 
	            { 
	                $StringTMP = substr($String,$I,3); 
	                $I = $I + 3; 
	            } 
	            elseif( ord($StringTMP) >=192 ) 
	            { 
	                $StringTMP = substr($String,$I,2); 
	                $I = $I + 2; 
	            } 
	            else 
	            { 
	                $I = $I + 1; 
	            } 
	            $StringLast[] = $StringTMP; 
	        } 
	        $StringLast = implode("",$StringLast); 
	        if($Append) 
	        { 
	            $StringLast .= "..."; 
	        } 
	        return $StringLast; 
	    } 
	}
	
	  public static function getCityDictHtml($provinceId=1,$cityId=22,$countyId=3){
	      require_once '../app/services/AreaService.php';
	      $areaService = new AreaService();
		  $param1 = array(0,1);
		  $provinces = $areaService->getAreaDicts($param1);
		  $param2 = array($provinceId,2);
		  $cities = $areaService->getAreaDicts($param2);
		  $param3 = array($cityId,3);
		  $counties = $areaService->getAreaDicts($param3);
		  
		  
	  	  $defaultOption = "<option value=''>".SELECTLABEL."</option>";
	  	  $hidden = "<input type='hidden' id='defaultOption' value='".SELECTLABEL."' />";
    	
    	  $html = "<select id='province' style='width: 5em;' onchange='javascript:AreaDict.changeArea(2)' onblur='javascript:AreaDict.validateAreaDict();' name='province'>";
    	  $html .= $defaultOption;
    	  foreach($provinces as $province){
    	  	   $selected = '';
    	  	   if($province['id']==$provinceId){
    	  	   	   $selected = 'selected=selected';
    	  	   }
    	  	   $option = "<option value='".$province['id']."'" .$selected.">".$province['title']."</option>";
    	  	   $html .= $option;
    	  }
    	  $html .= "</select><select id='city' style='width: 5em;' onchange='javascript:AreaDict.changeArea(3)' onblur='javascript:AreaDict.validateAreaDict();' name='city'>";
    	  $html .= $defaultOption;
    	  foreach($cities as $city){
    	  	   $selected = '';
    	  	   if($city['id']==$cityId){
    	  	   	   $selected = 'selected=selected'; 
    	  	   }
    	  	   $option = "<option value='".$city['id']."'" .$selected.">".$city['title']."</option>";
    	  	   $html .= $option;
    	  }
    	  $html .= "</select><select id='county' style='width: 5em;' onblur='javascript:AreaDict.validateAreaDict();'  name='county'>";
    	  $html .= $defaultOption;
    	  foreach($counties as $county){
    	  	   $selected = '';
    	  	   if($county['id']==$countyId){
    	  	   	   $selected = 'selected=selected'; 
    	  	   }
    	  	   $option = "<option value='".$county['id']."'" .$selected.">".$county['title']."</option>";
    	  	   $html .= $option;
    	  }
    	  $html .= "</select>";
    	  $html .= $hidden;
    	  return $html;
    	
    }
    
    /**
     * 从字符串开始位置截取中英文字符串
     * 可以解决中文截取时乱码情况（字符串必须是utf-8格式）
     * $length：如果有中文，一个中文占3个长度
     */
	public static function str_cut($str_cut,$length){
	
	    if(strlen($str_cut) > $length){
	       for($i=0; $i < $length; $i++){
	           if (ord($str_cut[$i]) > 128) $i++; 
	       }
	       $str_cut = substr($str_cut,0,$i); 
	   }
	   return $str_cut;
	}

}


